public class AdjustCityMonthlyBudget
{
    
    public String msg{get;set;}
    public String msg1{get;set;}
    public String IdSelect{get;set;}
    public Boolean DisplayApprove{get;set;}
    public Boolean DisplayReject{get;set;}
    public Boolean DisplaySubmit{get;set;}
    public Boolean DisplaySave{get;set;}
    public Boolean DisplayAllocate{get;set;}
    public Boolean DisplayTotal{get;set;}
    public Boolean InsertRecord;

    public Decimal TotalAdjustKG{get;set;}
    public Decimal TotalAllocatedKG{get;set;}
    public Decimal TotalRemainingKG{get;set;}
    public Decimal TotalAdjustRMB{get;set;}
    public Decimal TotalAllocatedRMB{get;set;}
    public Decimal TotalRemainingRMB{get;set;} 
    

    public Boolean ForUpdate;
    
    public String RSM_eMail;
    public String RGM_eMail;
    public String NMMM_eMail;
    
    String CityHead;
    String SalesCity;     
    public Boolean TestServer;
    
    List<CityBudget__c> SelectedRecordList = new  List<CityBudget__c>();
    List<CityBudget__c> SelectedBudgetList = new List<CityBudget__c>();
    public PE_Sample_Management__c PESM 
    {
         get{
             if(PESM == null)
                 PESM = new PE_Sample_Management__c();
             return PESM ;
         }
         set;
    }  
        
    Integer Inequality = 0;    
    
    public CityBudget__c CityBudget{
         get{
             if(CityBudget== null)
                 CityBudget= new CityBudget__c();
             return CityBudget;
         }
         set;
    }  
    public CityMonthlyBudget__c CityMonthlyBudget{
         get{
             if(CityMonthlyBudget== null)
                 CityMonthlyBudget= new CityMonthlyBudget__c();
             return CityMonthlyBudget;
         }
         set;
    }
    public List<CityMonthlyBudget__c> AmountBudget{
         get{
             if(AmountBudget== null)
                 AmountBudget= new List<CityMonthlyBudget__c> ();
             return AmountBudget;
         }
         set;
    }
    
    public Sub_Region_Budget__c SRB {
         get{
             if(SRB == null)
                 SRB = new Sub_Region_Budget__c();
             return SRB ;
         }
         set;
    }      
        
    public List<TableItemControl> TableItemsDown{         
        get{
             if(TableItemsDown== null)
                 TableItemsDown= new List<TableItemControl>();
             return TableItemsDown;
         }
        set;
    }    
    
    public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');     
        }  
        set;
    }
    
    public List<CityBudget__c> ExistRecord = new List<CityBudget__c>();
    public CityBudget__c SelectedRecord{
        get{        
             if(SelectedRecord== null)
                 SelectedRecord= new CityBudget__c();
             return SelectedRecord;
        }  
        set;
    }
    public List<Place__c> pList = new  List<Place__c>();  
    User cu  = [Select Name,UserRoleId,ProfileId,Title__c From User Where Id =:UserInfo.getUserId()];
    UserRole ur = [Select Id,Name,ParentRoleId  From UserRole Where Id =: cu.UserRoleId]; 

    UserRole RoleNationalMarketing = [Select u.Name, u.Id From UserRole u Where u.Name =: GlobalProperties.RoleNMMKTM];
    UserRole RoleNMKD = [Select u.Name, u.Id From UserRole u Where u.Name =: GlobalProperties.RoleNMKD];
    RecordType BufferRecord = [Select r.Name, r.Id From RecordType r Where Name =: GlobalProperties.CityMonthlyBuffer];
    Profile RSM= [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_M];
    Profile RSTM= [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_TM];
    Profile RGM= [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRGM];
    
    
    // get the city list                
    public List<SelectOption> options{
        get{
             if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();
                
            CityBudget.Year__c = SRB.Year__c;
            CityBudget.Rate__c = SRB.Rate__c;
            CityBudget.TotalBudgetkg__c = SRB.Total_budget_kg__c;
            CityBudget.TotalBudgetRMB__c = SRB.Total_budget_RMB__c;
            options.add(new SelectOption('1',' '));                    
            if((cu.ProfileId == RSM.id)||(cu.ProfileId == RSTM.id)||(cu.ProfileId == RGM.id)||(ur.id == RoleNMKD.id))
            {
               List<CityBudget__c> SelectedRecordBufferList = [Select  c.SalesCity__c,c.CityHead__c,c.ConversionForcast__c, c.InMarketValueHide__c  From CityBudget__c c Where c.SubRegionBudget__c =: UrlId and AdjustmentSubmit__c =: true];
               
               for(CityBudget__c c : SelectedRecordBufferList)
               {
                   options.add(new SelectOption(c.CityHead__c + ':' + c.SalesCity__c ,c.SalesCity__c));
               }               
            }
            else{
                
               List<CityBudget__c> SelectedRecordBufferList = [Select  c.SalesCity__c,c.CityHead__c  From CityBudget__c c Where c.SubRegionBudget__c =: UrlId];
               
               for(CityBudget__c c : SelectedRecordBufferList)
               {
                   Boolean haveThisCity = false;
                   for(SelectOption s :options){
                       if(s.getLabel() == c.SalesCity__c)
                       {
                           haveThisCity = true;
                       }
                   }
                   if(!haveThisCity)
                       options.add(new SelectOption(c.CityHead__c + ':' + c.SalesCity__c ,c.SalesCity__c));
               }              
            }

            return  options;
        }
        set;
    } 
    

    
    public PageReference actionSupport()
    {
        ForUpdate = false;
        DisplayAllocate = false;
        msg1= null;

        for(SelectOption s : options)
        {
            if(s.getValue() == IdSelect)
            {
                CityHead = s.getValue().split(':', 2)[0];
                SalesCity = s.getLabel();            
            }
        }

        if((CityHead == 'null')||(CityHead == ''))
        {
            CityHead = null;
        }

        List<AggregateResult> BufferAmount = [Select sum(c.BudgetRMB__c) RMB , sum(c.BudgetKg__c)KG From CityMonthlyBudget__c c Where 
           c.RecordType__c =: 'Buffer' and  c.PEManagement__c =: string.valueof(PESM.id).substring(0,15)];

       TotalAllocatedKG  = (Decimal)BufferAmount[0].get('KG');
       if(TotalAllocatedKG  == null)
       {
           TotalAllocatedKG  = 0;
       }
       TotalAllocatedRMB = (Decimal)BufferAmount[0].get('RMB');
       if(TotalAllocatedRMB == null)
       {
           TotalAllocatedRMB = 0;
       }
       
       TotalRemainingKG = TotalAdjustKG - TotalAllocatedKG;
       TotalRemainingRMB = TotalRemainingKG * SRB.Rate__c;    
                 
        SelectedBudgetList = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, AdjustmentSubmit__c,AdjustmentApprove__c,
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c,c.RSM__c , 
                c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c,  c.ConversionForcast__c,c.InMarketValueHide__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,
                c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
                c.name =: SRB.Year__c +'年'+ SalesCity + '专业样品管理' and c.SubRegionBudget__c =: UrlId and c.CityHead__c =: CityHead];  

        List<AggregateResult> TotalLastYearInMarketSales = [Select sum(InMarketSaleskg__c)InMarketSales, Month__c Mon From 
           InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: integer.valueof(SRB.Year__c)-1  and SalesCity__c =: SalesCity group by Month__c]; 
        List<AggregateResult> TotalThisYearInMarketSales = [Select sum(InMarketSalesForcast__c)InMarketSales, Month__c Mon From 
           InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: integer.valueof(SRB.Year__c)  and SalesCity__c =: SalesCity group by Month__c];                 
    
        List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)kg,Month__c Mon From Shipment__c Where KG__c > 0 and   Year__c =: integer.valueof(SRB.Year__c)-1 and SalesCity__c =: SalesCity and CalcInKg__c =: true group by Month__c];

        List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn,Month__c Mon  From 
                                      Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(integer.valueof(SRB.Year__c)-1) and Sales_city__c =: SalesCity group by Month__c];
        
        List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                      Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(integer.valueof(SRB.Year__c)) and Sales_city__c =: SalesCity group by Month__c];
          
        Decimal TotalLastYearPEShipmentValue = 0;

        Decimal TotalSubRegionLastYearInMarketSalesValue = 0;
        Decimal TotalSubRegionThisYearInMarketSalesValue = 0;                
        Decimal TotalLastYearPEConversionValue = 0;
        Decimal TotalThisYearPEConversionValue = 0;       
       
        TableItemsDown.clear();
        AmountBudget.clear();
        
       List<CityBudget__c> SelectedRecordBufferList = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
            c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RSM__c , c.NeedRSMAllocate__c,
            c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.CityHead__c, c.ConversionForcast__c,c.InMarketValueHide__c,
            c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
            c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,c.ApprovalStatus__c,
            c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
            c.name =: SRB.Year__c +'年'+ SalesCity + '专业样品管理' and c.SubRegionBudget__c =: UrlId and NeedRSMAllocate__c =: true];

      Integer StartMon = 1;
      List<CityMonthlyBudget__c> RsmMonthlyBuffer = [Select c.Year__c, c.ThisYearPESampleKg__c, c.BudgetAllocatedKG__c ,
                    c.ThisYearInMarketSalesKg__c,  c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c, c.ConversionForcast__c,c.InMarketValueHide__c,
                    c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
                    c.BudgetKg__c,c.CreatedDate  From CityMonthlyBudget__c c Where c.SubRegionBudget__c =: UrlId and c.RecordType__c =: 'Buffer'];                 
        
      List<CityMonthlyBudget__c> RsmMonthlyBudget = [Select c.Year__c, c.ThisYearPESampleKg__c, c.BudgetAllocatedKG__c ,
                    c.ThisYearInMarketSalesKg__c, c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c, c.ConversionForcast__c,c.InMarketValueHide__c,
                    c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
                    c.BudgetKg__c,c.CreatedDate  From CityMonthlyBudget__c c Where c.SubRegionBudget__c =: UrlId and c.RecordType__c =: 'Budget'];                 
              
        if(Date.Today().Month() <= 3)
        {
            StartMon = 4;
        }
        else if(Date.Today().Month() <= 6)
        {
            StartMon = 7;
        }
        else if(Date.Today().Month() <= 9)
        {
            StartMon = 10;
        }        
        else if(Date.Today().Month() <= 12)
        {
            StartMon = 1;
        }                     


        for(Integer i = StartMon; i < 13;i++)
        {
            TableItemControl T = new TableItemControl();
            T.Str = String.valueof(i);
            
            Decimal LastYearPEShipmentValue = 0;

            Decimal SubRegionLastYearInMarketSalesValue = 0;
            Decimal SubRegionThisYearInMarketSalesValue = 0;                
            Decimal LastYearPEConversionValue = 0;
            Decimal ThisYearPEConversionValue = 0;
            for(AggregateResult ag : TotalLastYearInMarketSales)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    SubRegionLastYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                    TotalSubRegionLastYearInMarketSalesValue += SubRegionLastYearInMarketSalesValue;
                }
            }                
            for(AggregateResult ag : TotalThisYearInMarketSales)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    SubRegionThisYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                    TotalSubRegionThisYearInMarketSalesValue += SubRegionThisYearInMarketSalesValue;
                }
            }  
            for(AggregateResult ag : TotalLastYearPEShipment)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    LastYearPEShipmentValue = (Decimal)ag.get('kg');
                    TotalLastYearPEShipmentValue += LastYearPEShipmentValue;
                }
            }  

            for(AggregateResult ag : SubRegionLastYearPEConversion)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    LastYearPEConversionValue = (Decimal)ag.get('TotalIn');
                    TotalLastYearPEConversionValue += LastYearPEConversionValue;
                }
            }                                                  
            for(AggregateResult ag : SubRegionThisYearPEConversion)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    ThisYearPEConversionValue = (Decimal)ag.get('TotalIn');
                    TotalThisYearPEConversionValue += ThisYearPEConversionValue;
                }
            }

            if(LastYearPEShipmentValue > 0)
                T.CMB.LastYearInMarketSaleskg__c= SubRegionLastYearInMarketSalesValue / LastYearPEShipmentValue;
            else
                T.CMB.LastYearInMarketSaleskg__c = 0;
            if(LastYearPEConversionValue > 0)   
                T.CMB.LastYearPESamplekg__c = LastYearPEShipmentValue / LastYearPEConversionValue;
            else
                T.CMB.LastYearPESamplekg__c = 0;
                
            T.CMB.ThisYearInMarketSalesKg__c = 0;
            T.CMB.ThisYearPESampleKg__c = 0;
            T.CMB.ConversionForcast__c = ThisYearPEConversionValue;
            T.CMB.InMarketValueHide__c = SubRegionThisYearInMarketSalesValue; 
            T.CMB.BudgetAllocatedKG__c = 0;                    
            
            TableItemsDown.add(T);
            }
            Decimal TotalBudgetAllocatedKG  = 0;
            List<CityMonthlyBudget__c> existMonBudget = [Select c.Id, c.ConversionForcast__c,c.InMarketValueHide__c,c.SalesCity__c, c.Month__c,c.BudgetKg__c,c.CityBudget__c,c.BudgetAllocatedKG__c  From CityMonthlyBudget__c c 
                Where c.SubRegionBudget__c =: UrlId and c.SalesCity__c =: SalesCity  and c.RecordType__c =: 'Budget'];
           
            
            if(existMonBudget.size() > 0){  
                for(CityMonthlyBudget__c sr : existMonBudget)
                {
                    for(TableItemControl t1 : TableItemsDown)
                    {
                        if( sr.Month__c == t1.str)
                        {
                            if(sr.BudgetKg__c > 0)
                            {
                                if((t1.CMB.BudgetAllocatedKG__c!= null)&&(t1.CMB.BudgetAllocatedKG__c == 0))
                                {
                                    t1.CMB.BudgetAllocatedKG__c = sr.BudgetKg__c;
                                }
                                else
                                {
                                    t1.CMB.BudgetAllocatedKG__c = t1.CMB.BudgetAllocatedKG__c + sr.BudgetKg__c;
                                }
                                if(TotalBudgetAllocatedKG == 0)
                                {
                                    TotalBudgetAllocatedKG  = sr.BudgetKg__c;
                                }
                                else
                                {
                                    TotalBudgetAllocatedKG  += sr.BudgetKg__c;
                                }                                    
                                
                                
                            } 
                                
                        }
                    }
                }
            } 

     
        CityMonthlyBudget__c srmb = new CityMonthlyBudget__c();
        srmb.Name = '合计';
        if(TotalLastYearPEShipmentValue > 0)
            srmb.LastYearInMarketSaleskg__c= TotalSubRegionLastYearInMarketSalesValue / TotalLastYearPEShipmentValue ;
        else
            srmb.LastYearInMarketSaleskg__c = 0;
        if(TotalLastYearPEConversionValue > 0)   
            srmb.LastYearPESamplekg__c = TotalLastYearPEShipmentValue / TotalLastYearPEConversionValue ;
        else
            srmb.LastYearPESamplekg__c = 0;
            
        srmb.ThisYearInMarketSalesKg__c = 0;
        srmb.ThisYearPESampleKg__c = 0;
        srmb.ConversionForcast__c = TotalThisYearPEConversionValue;
        srmb.InMarketValueHide__c = TotalSubRegionThisYearInMarketSalesValue;
                    
        srmb.BudgetAllocatedKG__c = TotalBudgetAllocatedKG;        
        AmountBudget.add(srmb);
       
        
       SelectedRecordList = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
            c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RSM__c ,c.NeedRSMAllocate__c,
            c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.CityHead__c, c.ConversionForcast__c,c.InMarketValueHide__c,
            c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
            c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,c.ApprovalStatus__c,
            c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
            c.name =: SRB.Year__c +'年'+ SalesCity + '专业样品管理' and c.SubRegionBudget__c =: UrlId ];
       
       String compareString;
       for(CityBudget__c c : SelectedRecordList)
       {
           if(c.ApprovalStatus__c != null)
           {
               compareString = c.ApprovalStatus__c;
               if(c.ApprovalStatus__c == '等待片区区经理审批')
               {    
                   compareString = '等待片区区经理审批';
                   break;
               }
                   
           }
           
       }
       
       
       if(SelectedRecordList.size() > 0 )
       {
           if(((compareString  == '等待大区经理审批')||(compareString  == '等待全国医药市场总监审批')||(compareString  == '审批通过'))&&(cu.UserRoleId != RoleNationalMarketing.id))
           {
                SelectedRecordList = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
                    c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RSM__c ,c.NeedRSMAllocate__c,
                    c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.CityHead__c, c.ConversionForcast__c,c.InMarketValueHide__c,
                    c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                    c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,c.ApprovalStatus__c,
                    c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
                    c.name =: SRB.Year__c +'年'+ SalesCity + '专业样品管理' and c.SubRegionBudget__c =: UrlId and c.CityHead__c =: CityHead ];
           }
       } 

        //
        if(SelectedRecordList.size() > 0){
            if(SelectedRecordList.size() > 1)
            {
                if(SelectedRecordBufferList.size() > 0){
                    SelectedRecord = SelectedRecordBufferList[0];
                    if(cu.ProfileId == RSM.id)
                        DisplayAllocate = true;

                }         
                else{
                    if(cu.UserRoleId == RoleNationalMarketing.id){
                        Place__c SelectCity = [Select id,name From Place__c Where PlaceType__c =: GlobalProperties.CityType and Name =: SalesCity];                  
                        SelectedRecord = new CityBudget__c();
                        SelectedRecord.ownerid = SelectedRecordList[0].RSM__c;
                        SelectedRecord.Place__c = SelectCity.id;
                        SelectedRecord.BufferSubmit__c = true;
                        SelectedRecord.NeedRSMAllocate__c = true;
                        SelectedRecord.SubRegionBudget__c = UrlId;
                        SelectedRecord.name = SRB.Year__c +'年'+ SalesCity + '专业样品管理';
                        SelectedRecord.Rate__c = SRB.Rate__c;
                        SelectedRecord.Year__c = SRB.Year__c;
                        insert SelectedRecord;
                        InsertRecord = true;
                    }
                }
            }
            else{
                SelectedRecord = SelectedRecordList[0];     
            }
            List<CityMonthlyBudget__c> existMonBud = [Select c.Year__c, c.ThisYearPESampleKg__c, c.BudgetAllocatedKG__c ,
                c.ThisYearInMarketSalesKg__c,c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c, c.ConversionForcast__c,c.InMarketValueHide__c,
                c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, c.RecordType__c,
                c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c =: SelectedRecord.id and c.RecordType__c =: 'Buffer'];
            
                                   
            if(existMonBud.size() > 0){
                ForUpdate = true;
                for(CityMonthlyBudget__c sr : existMonBud)
                {
                    for(TableItemControl t1 : TableItemsDown)
                    {
                        if( sr.Month__c == t1.str)
                        { 
                            t1.CMB = sr;
                        }
                    }
                }
            } 
                    for(TableItemControl t1 : TableItemsDown)
                    {
                        if(t1.CMB.BudgetKg__c > 0)
                        {
                            if(AmountBudget[0].BudgetKg__c > 0)
                                AmountBudget[0].BudgetKg__c += t1.CMB.BudgetKg__c;
                            else
                                 AmountBudget[0].BudgetKg__c = t1.CMB.BudgetKg__c;
                        }
                            
                    }
                    if(AmountBudget[0].BudgetKg__c != null)
                        AmountBudget[0].BudgetRMB__c = AmountBudget[0].BudgetKg__c * SRB.Rate__c;            
             
        }            
                 

        return null;
    } 

    public AdjustCityMonthlyBudget(){
    
       // try{    
        DisplayAllocate = false;
        DisplaySubmit = true;
        DisplayApprove = false;  
        DisplaySave = true;
        DisplayReject = DisplayApprove;
        InsertRecord = false;
        msg1= null;
        
        TestServer = true;
        TestServer__c ex=TestServer__c.getValues('TestOrNot');
        TestServer = ex.Test__c;
        
        if((cu.UserRoleId == RoleNationalMarketing.id)||(cu.UserRoleId == RoleNMKD.id))
            DisplayTotal = true;
        else
            DisplayTotal = false; 
        
        SRB = [Select s.total_score__c, s.potential_score__c, s.final_weighting__c, s.Year__c, s.Total_budget_kg__c,s.NMMMEmail__c ,
            s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, s.This_year_In_market_sales_kg__c, 
            s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, s.Rate__c, s.Place__c, s.PE_Sample_Management__c, 
            s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c, s.Last_year_conversion_weighting__c, 
            s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c,s.Id, s.Area__c, s.ApprovedFormula__c ,s.ApprovalStatusFormula__c
            From Sub_Region_Budget__c s Where s.id =: UrlId];
       NMMM_eMail = SRB.NMMMEmail__c;
       
       PESM = [Select id,rate__c, Budget_hold_in_HQ_Budget_allocation_kg__c,Budget_hold_in_HQ_RMB__c From PE_Sample_Management__c Where id =: SRB.PE_Sample_Management__c];
       TotalAdjustKG = PESM.Budget_hold_in_HQ_Budget_allocation_kg__c;
       TotalAdjustRMB = PESM.Budget_hold_in_HQ_RMB__c;
       List<AggregateResult> BufferAmount = [Select sum(c.BudgetRMB__c) RMB , sum(c.BudgetKg__c)KG From CityMonthlyBudget__c c Where 
           c.RecordType__c =: 'Buffer' and  c.PEManagement__c =: string.valueof(PESM.id).substring(0,15)];

       TotalAllocatedKG  = (Decimal)BufferAmount[0].get('KG');
       if(TotalAllocatedKG  == null)
       {
           TotalAllocatedKG  = 0;
       }
       TotalAllocatedRMB = (Decimal)BufferAmount[0].get('RMB');
       if(TotalAllocatedRMB == null)
       {
           TotalAllocatedRMB = 0;
       }       
       if(SRB.ApprovalStatusFormula__c != '审批通过')
       {
           msg = '样品管理未通过审批！';
           DisplaySubmit = false;
           DisplayApprove = false;
           DisplayReject = DisplayApprove;  
       }
       else
       {
            ExistRecord = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c,c.RGMEmail__c,c.RSMEmail__c, 
                c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.RSM__c, c.ConversionForcast__c,c.InMarketValueHide__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.ApprovalStatus__c,
                c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Submit__c,c.Changed__c  From CityBudget__c c Where c.SubRegionBudget__c =: UrlId and  AdjustmentSubmit__c =: true];                      
            List<CityBudget__c> ExistCityBudget = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RGMEmail__c,c.RSMEmail__c,
                c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.RSM__c, c.ConversionForcast__c,c.InMarketValueHide__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.ApprovalStatus__c,
                c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Submit__c,c.Changed__c  From CityBudget__c c Where c.SubRegionBudget__c =: UrlId ];                      
            
           for(CityBudget__c c : ExistCityBudget)
           {
               if(c.RGMEmail__c != null)
               {
                   RGM_eMail = c.RGMEmail__c;
               }
               if(c.RSMEmail__c != null)
               {
                   RSM_eMail = c.RSMEmail__c;
               }                       
           }
                                     
            if((ExistRecord.size()<= 0)&&(cu.UserRoleId == RoleNationalMarketing.id))
            {
                DisplaySubmit = true;
                DisplayApprove = false;
                DisplayReject = DisplayApprove;
            }
            else if((ExistRecord.size()<= 0)&&(cu.UserRoleId == RoleNationalMarketing.id))
            {
                msg = '城市样品未进行调整';
                DisplaySubmit = false;
                DisplayApprove = false;
                DisplayReject = DisplayApprove;            
            }
            else if(ExistRecord.size() > 0){
               
               if((cu.ProfileId != RGM.id)&&(cu.ProfileId != RSM.id)&&(cu.ProfileId != RSTM.id)&&(ExistRecord[0].ApprovalStatus__c != '审批通过') && (ExistRecord[0].AdjustmentSubmit__c == true) && (cu.UserRoleId != RoleNMKD.id))
               {
                    msg = '已提交审批，不能再修改！';
                    DisplaySave = false;
                    DisplaySubmit = false;
                    DisplayApprove = false; 
                    DisplayReject = DisplayApprove;                      
               }
               else{        
                   if(cu.UserRoleId == RoleNMKD.id){
                       if(ExistRecord[0].ApprovalStatus__c == '等待大区经理审批'){
                            msg = '等待大区经理审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;  
                            DisplayReject = false;                       
                       }
                       else if(ExistRecord[0].ApprovalStatus__c == '等待片区经理审批')
                       {
                            msg = '等待片区经理审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;   
                            DisplayReject = false;                         
                       }                       
                       else if(ExistRecord[0].ApprovalStatus__c == '审批通过')
                       {
                            msg = '审批通过';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;  
                            DisplayReject = false;                          
                       }
                       else{
                            DisplaySubmit = false;
                            DisplaySave = true;
                            DisplayApprove = true;  
                            DisplayReject = false;  
                       }                        
         
                   }
                   if((cu.ProfileId == RSM.id)||(cu.ProfileId == RSTM.id))
                   {
                       if(ExistRecord[0].ApprovalStatus__c == '等待大区经理审批'){
                            msg = '等待大区经理审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;
                            DisplayReject = DisplayApprove;                         
                       }
                       else if(ExistRecord[0].ApprovalStatus__c == '等待全国医药市场总监审批')
                       {
                            msg = '等待全国医药市场总监审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false; 
                            DisplayReject = DisplayApprove;                         
                       }                       
                       else if(ExistRecord[0].ApprovalStatus__c == '审批通过')
                       {
                            msg = '审批通过';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;
                            DisplayReject = DisplayApprove;                          
                       }
                       else{
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = true;
                            DisplayReject = DisplayApprove;
                       }
                   }
                   if((cu.ProfileId == RGM.id))
                   {
                       if(ExistRecord[0].ApprovalStatus__c == '等待片区经理审批'){
                            msg = '等待片区经理审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;    
                            DisplayReject = DisplayApprove;                     
                       }
                       else if(ExistRecord[0].ApprovalStatus__c == '等待全国医药市场总监审批')
                       {
                            msg = '等待全国医药市场总监审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;   
                            DisplayReject = DisplayApprove;                       
                       }                       
                       else if(ExistRecord[0].ApprovalStatus__c == '审批通过')
                       {
                            msg = '审批通过';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;    
                            DisplayReject = DisplayApprove;                      
                       }
                       else{
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = true;
                            DisplayReject = DisplayApprove;
                       }                   
                   }                   
                   if(cu.UserRoleId == RoleNationalMarketing.id){
                       if(ExistRecord[0].ApprovalStatus__c == '等待片区经理审批'){
                            msg = '等待片区经理审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;  
                            DisplayReject = DisplayApprove;                       
                       }
                       else if(ExistRecord[0].ApprovalStatus__c == '等待全国医药市场总监审批')
                       {
                            msg = '等待全国医药市场总监审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;  
                            DisplayReject = DisplayApprove;                        
                       }                       
                       else if(ExistRecord[0].ApprovalStatus__c == '等待大区经理审批')
                       {
                            msg = '等待大区经理审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;  
                            DisplayReject = DisplayApprove;                        
                       }
                       else{
                            DisplaySubmit = false;
                            DisplaySave = true;
                            DisplayApprove = true;
                            DisplayReject = DisplayApprove;
                       }  
                       
                   } 
                } 
            }  
        }
        /*
        }
        catch (DmlException e) {
            ApexPages.addMessages(e);
        } 
        */
    }

    public void SetRecord(Boolean Submit)
    {
       if( cu.UserRoleId == RoleNMKD.id)
       {
           SelectedRecord.NMDChanged__c = true;
       } 
       
       if(cu.UserRoleId == RoleNationalMarketing.id)
           SelectedRecord.BufferSubmit__c = true;
       if(SelectedRecord.id != null)
           update SelectedRecord;
 
        List<CityMonthlyBudget__c> ExistSubregionalMB = new List<CityMonthlyBudget__c>();
        if(SelectedRecord != null)
            ExistSubregionalMB = [Select id,Month__c,BudgetAllocatedKG__c, ConversionForcast__c, InMarketValueHide__c  From CityMonthlyBudget__c Where CityBudget__c =: SelectedRecord.id ];
        // set table items up
        List<CityMonthlyBudget__c> CityBudgetMonBudgetList = new List<CityMonthlyBudget__c>();
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '合计')
            {
                continue;
            }

            t.CMB.Name = SRB.Year__c + '年' + SalesCity + t.str + '月专业样品管理';
            t.CMB.Month__c = t.str;
            
            if(t.CMB.BudgetKg__c != null)
            {
                t.CMB.BudgetRMB__c =  t.CMB.BudgetKg__c *  SelectedRecord.Rate__c;
            }
            
            if((t.CMB.BudgetKg__c + t.CMB.BudgetAllocatedKG__c > 0)&&(t.CMB.InMarketValueHide__c > 0))
                t.CMB.ThisYearInMarketSalesKg__c = t.CMB.InMarketValueHide__c / (t.CMB.BudgetKg__c + t.CMB.BudgetAllocatedKG__c);
            else
                t.CMB.ThisYearInMarketSalesKg__c = 0;    
            t.CMB.ThisYearInMarketSalesKg__c = t.CMB.ThisYearInMarketSalesKg__c.intValue();
            if(t.CMB.ConversionForcast__c > 0)
                t.CMB.ThisYearPESampleKg__c = (t.CMB.BudgetKg__c + t.CMB.BudgetAllocatedKG__c) / t.CMB.ConversionForcast__c;
            else
                t.CMB.ThisYearPESampleKg__c = 0;
            t.CMB.ThisYearPESampleKg__c = t.CMB.ThisYearPESampleKg__c.intValue(); 
                        
            if(!ForUpdate){          
                t.CMB.CityBudget__c = SelectedRecord.id;
                t.CMB.RecordTypeId = BufferRecord.id;
                
            }
            
            CityBudgetMonBudgetList.add(t.CMB);
        }
        if(CityBudgetMonBudgetList.size() > 0){
            if(ForUpdate)
            {
                update CityBudgetMonBudgetList;
            }
            else{
                insert CityBudgetMonBudgetList;
                ForUpdate = true;
            }  
       } 
       List<AggregateResult> BufferAmount = [Select sum(c.BudgetRMB__c) RMB , sum(c.BudgetKg__c)KG From CityMonthlyBudget__c c Where 
           c.RecordType__c =: 'Buffer' and c.CityBudget__r.BufferSubmit__c =: true and  PEManagement__c =: PESM.id];
       
       TotalAllocatedKG  = (Decimal)BufferAmount[0].get('KG');
       TotalAllocatedRMB = (Decimal)BufferAmount[0].get('RMB');           
             
    }


    public PageReference Save()
    {
        
        if(SRB.ApprovalStatusFormula__c  != '审批通过')
        {   
            return null;
        }
        
        InsertRecord = false;
        Decimal AllocatedNum = decimal.valueof(0);     
        
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '合计')
            {
                continue;
            }
            if((t.CMB.BudgetKg__c != null)&&(t.CMB.BudgetKg__c > 0)){
                if((AllocatedNum == null)||(AllocatedNum == 0))
                    AllocatedNum = t.CMB.BudgetKg__c;
                else
                    AllocatedNum += t.CMB.BudgetKg__c;
            }    
        } 
        
        SetRecord(false);
        msg1 = '保存成功!';  
        msg = null;    
        return null;
    }

    public PageReference Submit()
    {
       List<CityBudget__c> SelectedRecordBufferList = [Select  c.SalesCity__c,c.CityHead__c, c.ConversionForcast__c,c.InMarketValueHide__c  From CityBudget__c c Where c.SubRegionBudget__c =: UrlId];
               
        Set<CityBudget__c> SubmitSRBL = new Set<CityBudget__c>();
        for(CityBudget__c c : SelectedRecordBufferList)
        {
           List<CityBudget__c> SubmitSRB = [Select c.BufferKG__c , c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
                    c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RSM__c ,
                    c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c,  c.ConversionForcast__c,c.InMarketValueHide__c,
                    c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                    c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c, c.CityHead__c,
                    c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
                    c.name =: SRB.Year__c +'年' + c.SalesCity__c + '专业样品管理' and c.SubRegionBudget__c =: UrlId and (c.BufferSubmit__c =: true or c.ApprovalStatus__c =: '审批驳回')];             
           if(SubmitSRB.size() > 0)
           {
               if(SubmitSRB[0].BufferKG__c == 0)
               {
                   delete SubmitSRB[0];
               }
               else
               {
                   SubmitSRBL.add(SubmitSRB[0]);
               }
           }
               
        }
        

        List<id> cityheads = new List<id> ();
        List<CityBudget__c> updateList = new List<CityBudget__c> ();      
        for(CityBudget__c  s : SubmitSRBL)
        {    
            cityheads.add(s.CityHead__c);
            s.AdjustmentSubmit__c = true;
            s.BufferSubmit__c = true;
            s.ApprovalStatus__c = '等待片区经理审批';
            s.NMMMSubmit__c = true;
            updateList.add(s);
        }
        

        update updateList;
        
        // send request email to RSM
        if(updateList.size() > 0){
            List<String> toAddresses = new List<String>();
            if(RSM_eMail != null)
                toAddresses.add( RSM_eMail );  
            List<String> ccAddresses = new List<String>();
            String Body = '您好！\n' + '您收到一个新的' + updateList[0].SubRegion__c + '城市专业样品管理调整申请!\n' + string.valueof(Date.Today());
            String Subject = updateList[0].SubRegion__c + '申请';
            
            if(toAddresses.size() > 0)        
                EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);    
        }
        

        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
            
    public PageReference Cancel()
    {
        if(InsertRecord)
        {
            delete SelectedRecord;
        }
        
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
    public PageReference Approve()
    {
       list<CityBudget__c> DeleteCB = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, AdjustmentSubmit__c,AdjustmentApprove__c,
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RSM__c ,
                c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c,  c.ConversionForcast__c,c.InMarketValueHide__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,
                c.Id, c.FinalWeighting__c, c.Area__c,c.Allocated__c , c.Approved__c,c.Changed__c From CityBudget__c c Where 
                c.ownerid =: cu.id and c.SubRegionBudget__c =: UrlId and c.NeedRSMAllocate__c =: true and 
                (c.ApprovalStatus__c =: '等待片区经理审批' or c.ApprovalStatus__c =: '等待大区经理审批' or c.ApprovalStatus__c =: '等待全国医药市场总监审批')];   
        

        if(DeleteCB.size() > 0){    
            for(CityBudget__c c : DeleteCB )
            {
                if(c.Allocated__c == false)
                {
                    msg = c.name + '需要您进行分配！';
                    return null;
                }
            }      
        }  
                    
       list<CityBudget__c> SubmitSRBL = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, AdjustmentSubmit__c,AdjustmentApprove__c,
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RSM__c ,
                c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c,  c.ConversionForcast__c,c.InMarketValueHide__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,c.CityHead__r.Email,
                c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
                c.BufferKG__c >: 0 and c.SubRegionBudget__c =: UrlId and (c.ApprovalStatus__c =: '等待片区经理审批' or c.ApprovalStatus__c =: '等待大区经理审批' or c.ApprovalStatus__c =: '等待全国医药市场总监审批')];         

        for(CityBudget__c  s : SubmitSRBL)
        {
            
            if((cu.ProfileId == RSM.id)||(cu.ProfileId == RSTM.id))
            {
                s.ApprovalStatus__c = '等待大区经理审批';
                s.BufferSubmit__c = true;
                s.AdjustmentSubmit__c = true; 
                s.RSMSubmit__c = true;   
                                 
            }
                
            else if(cu.ProfileId == RGM.id)
            {
                s.ApprovalStatus__c = '等待全国医药市场总监审批';             
            }
            else if(cu.UserRoleId == RoleNMKD.id)
            {
                s.ApprovalStatus__c = '审批通过';
                s.AdjustmentSubmit__c = false; 
                s.AdjustmentApprove__c = false;
                s.BufferSubmit__c  = false;                     
                s.RSMSubmit__c = true;
                List<CityMonthlyBudget__c> RsmMonthlyBuffer = [Select c.Year__c, c.ThisYearPESampleKg__c, c.CreatedDate,c.IfRejectThenDel__c,
                    c.ThisYearInMarketSalesKg__c, c.SystemModstamp, c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c,
                    c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
                    c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c =: s.id and c.RecordType__c =: 'Buffer'];
               for(CityMonthlyBudget__c c : RsmMonthlyBuffer )
                {
                    c.IfRejectThenDel__c = false;
                }
                update RsmMonthlyBuffer; 
            }            
                
        }
        if((cu.ProfileId == RSM.id)||(cu.ProfileId == RSTM.id))
        {
            
            List <String> toAddresses = new List <String>();
            if(RGM_eMail != null)
                toAddresses.add( RGM_eMail );

            List<String> ccAddresses = new List<String>();
            String Body = '您好！\n' +  '您收到一个新的' + SubmitSRBL[0].SubRegion__c + '城市专业样品管理调整申请!\n'+ string.valueof(Date.Today());
            String Subject = SubmitSRBL[0].SubRegion__c + '申请';
            
            if(toAddresses.size() > 0)         
                EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);                         
        }
        else if(cu.ProfileId == RGM.id)
        {

            List <String> toAddresses = new List <String>();
            User NMKTD = [Select Email From user Where UserRoleId =: RoleNMKD.id limit 1];
            if(NMKTD.Email != null)
                toAddresses.add( NMKTD.Email );

            List<String> ccAddresses = new List<String>();
            String urlLink;
            if(TestServer)
            {
                urlLink = 'https://test.salesforce.com/apex/AdjustCityMonthlyBudget?id=' + UrlId;
            }
            else
            {
                urlLink = 'https://login.salesforce.com/apex/AdjustCityMonthlyBudget?id=' + UrlId;
            }
            String Body = '您好！\n' +  '您收到一个新的' + SubmitSRBL[0].SubRegion__c + '城市专业样品管理调整申请!\n'
                            + '链接: ' + urlLink + '\n'
                            + string.valueof(Date.Today());
            String Subject = SubmitSRBL[0].SubRegion__c + '申请';
            
            if(toAddresses.size() > 0)         
                EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);                   
        }
                    
        else if(cu.UserRoleId == RoleNMKD.id)
        {

            List <String> toAddresses = new List <String>();
            if(NMMM_eMail != null)
                toAddresses.add( NMMM_eMail );
            for(CityBudget__c s : SubmitSRBL)
            {
                if(s.CityHead__r.Email != null)
                    toAddresses.add(s.CityHead__r.Email);
            }
            
            List<String> ccAddresses = new List<String>();
            String urlLink;
            if(TestServer)
            {
                urlLink = 'https://test.salesforce.com/apex/AdjustCityMonthlyBudget?id=' + UrlId;
            }
            else
            {
                urlLink = 'https://login.salesforce.com/apex/AdjustCityMonthlyBudget?id=' + UrlId;
            }            
            String Body = '您好！\n' + SubmitSRBL[0].SubRegion__c + '城市专业样品管理调整申请，通过审批！\n' 
                           + '链接: ' + urlLink + '\n'
                        + string.valueof(Date.Today());
            String Subject = SubmitSRBL[0].SubRegion__c + '审批通过';
            
            if(toAddresses.size() > 0)         
                EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);                   
        }

        update SubmitSRBL;
        if(cu.UserRoleId == RoleNMKD.id)
        {
            if(DeleteCB.size() > 0)
                Delete DeleteCB;
        }    
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
    public PageReference Allocate()
    {       
        
        pageReference pr = page.AllocateCityMonthlyBuffer;
        pr.getParameters().put('id', UrlId+'?'+ SelectedRecord.name);
        return pr;        
    }
    public PageReference Reject()
    {
       List<CityBudget__c> SelectedRecordBufferList = [Select  c.SalesCity__c,c.CityHead__c, c.ConversionForcast__c,c.InMarketValueHide__c From CityBudget__c c Where c.SubRegionBudget__c =: UrlId];
                 
        Set<CityBudget__c> SubmitSRBL = new Set<CityBudget__c>();
        for(CityBudget__c c : SelectedRecordBufferList)
        {
           List<CityBudget__c> SubmitSRB = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
                    c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.RSM__c ,
                    c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.ConversionForcast__c,c.InMarketValueHide__c,
                    c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                    c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c, c.CityHead__c,
                    c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
                    c.name =: SRB.Year__c +'年' + c.SalesCity__c+ '专业样品管理' and c.SubRegionBudget__c =: UrlId and BufferSubmit__c =: true];             
           if(SubmitSRB.size() > 0)
           {
               for(integer num = 0; num < SubmitSRB.size(); num++)
               {
                   SubmitSRBL.add(SubmitSRB[num]);    
               }
           } 
        }

        List<id> cityheads = new List<id> ();
        List<CityBudget__c> updateList = new List<CityBudget__c> (); 
        List<CityBudget__c> delList = new List<CityBudget__c> ();

        List<String> RejectCBList = new List<String>();                     
        for(CityBudget__c  s : SubmitSRBL)
        {
            RejectCBList.add(s.id);             
            s.ApprovalStatus__c = '审批驳回';
            s.BufferSubmit__c  = false;
            s.AdjustmentSubmit__c = false;    
            s.AdjustmentApprove__c = false;    
            updateList.add(s);
            if(s.NeedRSMAllocate__c == true)
            {
                delList.add(s);
            }
        }
        update updateList;
        //delete delList;

        List<CityMonthlyBudget__c> RsmMonthlyBuffer = [Select c.Year__c, c.ThisYearPESampleKg__c, c.CreatedDate,c.IfRejectThenDel__c,
            c.ThisYearInMarketSalesKg__c, c.SystemModstamp, c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c,
            c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
            c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c in: RejectCBList and c.RecordType__c =: 'Buffer' and c.IfRejectThenDel__c =: true];
        delete RsmMonthlyBuffer;        
        
        // send request email to RSM
        List<String> toAddresses = new List<String>();
        if((cu.ProfileId == RSM.id)||(cu.ProfileId == RSTM.id))
        {
            if(NMMM_eMail != null)
                toAddresses.add( NMMM_eMail );  
        }
        else if(cu.ProfileId == RGM.id)
        {
            if(NMMM_eMail != null)
                toAddresses.add( NMMM_eMail );
            if(RSM_eMail != null)      
                toAddresses.add( RSM_eMail );
        }
        else if(cu.UserRoleId == RoleNMKD.id)
        {
            if(NMMM_eMail != null)
                toAddresses.add( NMMM_eMail );
            if(RSM_eMail != null)  
                toAddresses.add( RSM_eMail );
            if(RGM_eMail != null)
                toAddresses.add( RGM_eMail );       
        }
        
        if(updateList.size() > 0){
            List<String> ccAddresses = new List<String>();
            String Body = '您好！\n' + updateList[0].SubRegion__c + '城市专业样品管理调整申请，被驳回！\n' + string.valueof(Date.Today());
            String Subject = updateList[0].SubRegion__c + '审批驳回';
            
            if(toAddresses.size() > 0)         
                EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);    
        }
        
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;    
    }
    
    static testMethod void OverrideViewTest()
    {
       Profile p  = [select id from profile where name =: GlobalProperties.ProfileRMMM  ];
        UserRole SRMMM_SOC = [Select Id,Name From UserRole Where Name =: GlobalProperties.SRMMM_SOC];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8',UserRoleId = SRMMM_SOC.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='asdfdaa@testorg1.com');
        insert u1;
        
        System.runAs(u1) {
            PE_Sample_Management__c PE = new PE_Sample_Management__c();
            PE.WOC_Total_budget_RMB__c = 1;
            PE.Deal__c = true;
            PE.WOC_budget_allocation_kg__c = 2;
            PE.WOCInMarketValueHide__c = 0;
            PE.WOCConversionForcast__c = 0;                  
            PE.SOC_Total_budget_RMB__c = 0;
            PE.SOC_budget_allocation_kg__c = 0;
            PE.SOCInMarketValueHide__c = 0;
            PE.SOCConversionForcast__c = 0;                  
            PE.EOC_Total_budget_RMB__c = 0;
            PE.EOC_budget_allocation_kg__c = 0;
            PE.EOCInMarketValueHide__c = 0;
            PE.EOCConversionForcast__c = 0;            
            PE.NOC_Total_budget_RMB__c = 0;
            PE.NOC_budget_allocation_kg__c = 0;
            PE.NOCInMarketValueHide__c = 0;
            PE.NOCConversionForcast__c = 0;
            PE.Rate__c =2;
            PE.Total_Budget_Allocation_RMB__c = 1;
            PE.Budget_hold_in_HQ_Budget_allocation_kg__c = 10;
            insert PE;
            
            RegionalBudget__c RB = new RegionalBudget__c();
            RB.PESampleManagement__c = PE.id;
            RB.Approved__c = true;
            RB.ApprovalStatus__c = '审批通过';
            insert RB;
            
            Sub_Region_Budget__c SRB = new Sub_Region_Budget__c();
            SRB.PE_Sample_Management__c = PE.id;
            SRB.RegionalBudget__c = RB.id;
            SRB.Rate__c = 10;
            SRB.Name = '2012年华南一区专业样品管理';
            insert SRB;

            Profile pASM  = [select id from profile where name =: GlobalProperties.ProfileASM ];
            List<User> CH = [Select id,ManagerId From User Where profileId =: pASM.id  and IsActive =: true ];
            
            Place__C diFang = [Select id From Place__C Where Name =: '广州'];
            CityBudget__c CB = new CityBudget__c();
            CB.SubRegionBudget__c = SRB.id;
            CB.AdjustmentSubmit__c = true;
            CB.CityHead__c = CH[0].id;
            CB.Place__c = diFang.id; 
            CB.Rate__c = 10;
            insert CB;            
            
            
            test.setCurrentPageReference(Page.OverrideSubRegionBudgetNew);
            System.currentPageReference().getParameters().put('id', SRB.Id);          
            
            AdjustCityMonthlyBudget testCase = new AdjustCityMonthlyBudget();

            
      
            testCase.actionSupport();
       
            testCase.Submit();
            for(TableItemControl t : testCase.TableItemsDown){
                t.CMB.BudgetKg__c = 1;
                t.CMB.BudgetAllocatedKG__c =1;  
            }
            testCase.SelectedRecord.Rate__c = 10;
            testCase.SelectedRecord = CB;                
            testCase.Save();
            testCase.Approve();
            testCase.Cancel();
            testCase.Reject();
        }    
    }
 
}